# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： file_util
Description :
Author : 'li'
date： 2022/1/2
Change Activity:
2022/1/2:
-------------------------------------------------
"""
import hashlib
import os


def read_file_text(file_path, encoding='utf8'):
    """
    读取文件内容

    Args:
        file_path: 文件路径
        encoding: 编码

    Returns:
        文件内容

    """

    with open(file_path, mode='r', encoding=encoding) as file:
        lines = file.readlines()
        content = ''
        for line in lines:
            content = content + line
        return content


def try_read_file_text(file_path, encodings=('utf8', 'gbk', 'ascii')):
    """
    使用不同编码尝试读取文件

    Args:
        file_path: 文件路径
        encodings: 编码

    Returns:
        文件内容
    """
    for encoding in encodings:
        try:
            content = read_file_text(file_path, encoding)
            return content
        except Exception as e:
            print(e)
        raise Exception(f'read file {file_path} error !')


def read_lines(p, encoding='utf8'):
    """
    读取每行内容

    Args:
        p:文件路径
        encoding: 编码

    Returns:

    """
    """return the text in a file in lines as a list """
    f = open(p, 'r', encoding=encoding)
    return f.readlines()


def write_text(file_path, content, encoding='utf8'):
    """
    向文件写入内容

    Args:
        file_path: 文件路径
        content:  文件内容
        encoding:  编码

    """

    with open(file_path, mode='w', encoding=encoding) as file:
        file.write(content)


def get_file_md5(path):
    """
    获取文件md5

    Args:
        path: 文件路径

    Returns:
        md5
    """
    if not os.path.isfile(path):
        return
    my_hash = hashlib.md5()
    f = open(path, 'rb')
    while True:
        b = f.read(8096)
        if not b:
            break
        my_hash.update(b)
    f.close()
    return str(my_hash.hexdigest())
